package com.platform.comm.web.results;

import lombok.Data;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;

import java.util.stream.Collectors;

/**
 * Description: Elasticsearch Search DTO
 *
 * @author libin created on 2019/10/30
 */
@Data
public class EsJsonResult {
    public static final String OK = "0";

    public static final String FAILED = "-1";


    /**
     * 响应码
     */
    protected String code;

    /**
     * 响应消息
     */
    protected String message;


    public EsJsonResult copy(EsJsonResult other) {
        this.code = other.code;
        this.message = other.message;
        return this;
    }

    /**
     * New successful instance
     */
    public EsJsonResult() {
        this.code = OK;
    }

    /**
     * New failed instance
     */
    public EsJsonResult(String errMsg) {
        this.code = FAILED;
        this.message = errMsg;
    }

    public EsJsonResult succeed() {
        this.code = OK;
        this.message = null;
        return this;
    }

    public EsJsonResult fail(String errMsg) {
        this.code = FAILED;
        this.message = errMsg;
        return this;
    }

    public EsJsonResult apply(String code, String message) {
        this.code = code;
        this.message = message;
        return this;
    }

    /**
     * 根据binding生成JsonResult对象
     */
    public static EsJsonResult of(BindingResult binding) {
        EsJsonResult result = new EsJsonResult();
        if (binding.hasErrors()) {
            String errors = binding.getAllErrors()
                    .stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.joining(";"));
            result.fail(errors);
        }

        return result;
    }

    /**
     * 根据binding生成JsonResult对象
     */
    public static EsJsonResult of(Errors errors) {
        EsJsonResult result = new EsJsonResult();
        if (errors.hasErrors()) {
            String message = errors.getAllErrors()
                    .stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.joining(";"));
            result.fail(message);
        }
        return result;
    }

    public static EsJsonResult of(Exception e) {
        return new EsJsonResult(e.getMessage());
    }
}
